/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 */
// 成本中心
// 根据账套查询列表
import React from 'react';
import {connect} from 'react-redux';
import {Table, Button, Badge, Popover, Icon} from 'antd';
import CCService from 'containers/setting/cost-center/cost-center.service';
import SearchArea from 'components/search-area';
import menuRoute from 'routes/menuRoute';
import 'styles/setting/cost-center/cost-center.scss';
import {messages} from 'share/common';
import BaseService from 'share/base.service';
import ResizeTable from 'components/resize-table';

class CostCenter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      visible: false,
      columns: [
        {
          title: messages('common.sequence'),
          dataIndex: 'index',
          width: 48,
          render: (value, record, index) => this.state.pagination.pageSize * this.state.pagination.page + index + 1
        },
        {
          title: messages('setting.key353'/* 成本中心名称*/),
          dataIndex: 'name',
          width: '20%',
          render: text => <span>{text ? <Popover
placement="topLeft"
            overlayStyle={{width: 200}}
            content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('setting.key1518')/* 父级成本中心*/,
          dataIndex: 'parentCostCenterName',
          width: '20%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('setting.key198'/* 编码*/),
          dataIndex: 'code',
          width: '20%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('setting.key354'/* 状态*/),
          dataIndex: 'enabled',
          width: '20%',
          render: enabled => (
            <Badge
status={enabled ? 'success' : 'error'}
              text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>)
        },
        {
          title: messages('common.operation'), // "操作",
          dataIndex: 'id',
          render: (text, record) => (
            <span>
              <a onClick={e => this.editCostCenter(e, record)}>
                {messages('common.edit')}
              </a>
              &nbsp;&nbsp;&nbsp;
              <a onClick={e => this.detailCostCenter(e, record)}>
                {messages('common.detail')}
              </a>
            </span>)
        }
      ],
      pagination: {
        total: 0,
        page: 0,
        pageSize: 25, // 成本中心最多20个，我这边一次性加载
      },
      searchForm: [
        {
          type: 'select',
          id: 'setOfBook',
          label: messages('setting.key246'/* 账套*/),
          options: [],
          defaultValue: '',
          // 这个选项是外面传入，就不许下面参数
          // getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          // method: 'get',
          labelKey: 'setOfBooksCode',
          valueKey: 'id',
          event: 'setOfBooksCodeChange',
        },
      ],
      searchParams: {
        setOfBook: ''
      },
      newCostCenter: menuRoute.getRouteItem('new-cost-center', 'key'), // 新增成本中心
      CostCenterDetail: menuRoute.getRouteItem('cost-center-detail', 'key'), // 成本中心详情
      OrgStruture: menuRoute.getRouteItem('org-structure', 'key'), // 企业组织架构
      depIsCostCenter: false// 部门是否是成本中心
    };
  }

  componentDidMount() {
    this.getTenantAllSob();
    this.setState({
      depIsCostCenter: this.props.companyConfiguration.configuration.ui.showDepartmentSelector.applications
    });
  }

  componentWillReceiveProps(nextProps) {
  }

  getTenantAllSob() {
    // 给一个初始值
    const {searchForm, searchParams} = this.state;
    const _searchParams = this.getBeforePage('CostCenter');
    // 下面针对账套下拉单进行处理
    const setOfBookSelecter = searchForm[0];
    CCService.getTenantAllSob()
      .then((res) => {
        const options = res.data;
        const defaultValue = _searchParams.setOfBook ? _searchParams.setOfBook : options[0].id;
        options.map((item) => {
          item.label = item.setOfBooksName;
          item.value = item.id;
        });
        setOfBookSelecter.options = options;
        setOfBookSelecter.defaultValue = defaultValue;
        searchParams.setOfBook = defaultValue;
        this.clearBeforePage('CostCenter');
        this.setState({
          searchForm,
          searchParams,
        }, () => {
          this.getList();
        });
      });
  }

  // 得到列表数据
  getList() {
    this.setState({loading: true});
    const {searchParams, pagination} = this.state;
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      setOfBooksId: searchParams.setOfBook,
    };
    CCService.getCostCenterBySobId(params).then((response) => {
      response.data.map((item) => {
        item.key = item.id;
      });
      pagination.total = response.total;
      pagination.current = params.page + 1;
      this.setState({
        data: response.data,
        loading: false,
        pagination
      });
    });
  }

  // 新增成本中心
  handleNew = () => {
    const {searchParams, pagination, newCostCenter} = this.state;
    this.setBeforePage({...searchParams, page: pagination.page}, 'CostCenter');
    this.context.router.push(newCostCenter.url.replace(':id', 'NEW'));
  };

  // 编辑成本中心
  editCostCenter(e, record) {
    const {searchParams, pagination, CostCenterDetail} = this.state;
    this.setBeforePage({...searchParams, page: pagination.page}, 'CostCenter');
    this.context.router.push(this.state.newCostCenter.url.replace(':id', record.costCenterOID));
  }

  // 成本中心详情
  detailCostCenter(e, record) {
    const {searchParams, pagination, CostCenterDetail} = this.state;
    this.setBeforePage({...searchParams, page: pagination.page}, 'CostCenter');
    this.context.router.push(CostCenterDetail.url.replace(':id', record.costCenterOID));
  }

  // 分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getList();
    });
  };
  // 员工信息，工号，电话等关键字是及时搜索
  eventSearchAreaHandle = (e, item) => {
    const searchParams = this.state.searchParams;
    const pagination = this.state.pagination;
    pagination.page = 0;
    searchParams.setOfBook = item;
    this.setState({
      pagination,
      searchParams
    }, () => {
      this.getList();
    });
  }
  // 点击搜索
  search = (result) => {
    const pagination = this.state.pagination;
    pagination.page = 0;
    pagination.current = 1;
    pagination.total = 0;
    this.setState({
      pagination,
      searchParams: Object.assign(this.state.searchParams, result)
    }, () => {
      this.getList();
    });
  };
  clear = () => {
    this.setState({
      searchParams: {
        setOfBook: ''
      }
    });
  };

  render() {
    const {columns, data, loading, pagination, searchForm, depIsCostCenter} = this.state;
    const {tenantMode} = this.props;
    return (
      <div className="cost-center">
        <SearchArea
          eventHandle={this.eventSearchAreaHandle}
          isHideOkText
          isHideClearText
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}/>
        <div className="table-header">
          <div className="cost-center-dep-wrap" />
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          <div className="table-header-buttons">
            <Button type="primary" disabled={!tenantMode} onClick={this.handleNew}>
              {messages('common.create')}
            </Button>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey="id"
          bordered
          onChange={this.onChangePager}
          size="middle"
        />
      </div>
    );
  }

}

CostCenter.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    companyConfiguration: state.login.companyConfiguration,
  };
}

export default connect(mapStateToProps)(CostCenter);

